package com.ego.item.service.impl;

import com.ego.common.pojo.PageResult;
import com.ego.item.mapper.BrandMapper;
import com.ego.item.pojo.Brand;
import com.ego.item.service.BrandService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class BrandServiceImpl implements BrandService {
    @Autowired
    private BrandMapper brandMapper;

    @Override
    public PageResult<Brand> page(Integer pageNo, Integer pageSize, String sortBy, Boolean descending, String key) {
        //1.分页
        PageHelper.startPage(pageNo,pageSize);
        //2.查询条件
        Example example = new Example(Brand.class);
        Example.Criteria criteria = example.createCriteria();
        if(StringUtils.isNotBlank(key)){
            criteria.andLike("name","%"+key+"%")
                    .orEqualTo("letter",key.toUpperCase());
        }
        //3.排序
        if(StringUtils.isNotBlank(sortBy)){
            example.setOrderByClause(sortBy+" "+(descending?"desc":"asc"));
        }
        Page<Brand> page = (Page<Brand>)brandMapper.selectByExample(example);
        return new PageResult<>(page.getTotal(),page.getResult());
    }

    @Transactional
    @Override
    public void save(Brand brand, List<Integer> cids) {
        //1.保存品牌(insertSelective只会修改brand中有数据的字段)
        brandMapper.insertSelective(brand);
        //2.维护品牌和类别的关系
        if(cids!=null){
            cids.forEach(cid->{
                brandMapper.insertCategoryBrand(cid,brand.getId());
            });
        }
    }

    @Override
    public Brand findBybid(Long bid) {
        return brandMapper.selectByPrimaryKey(bid);
    }

    @Override
    public void update(Brand brand, List<Integer> cids) {
        //1.更新brand表
        brandMapper.updateByPrimaryKey(brand);
        //2.删除之前brand和category关系
        brandMapper.deleteCategoryBrand(brand.getId());
        //3.新增brand和category关系
        if(cids!=null){
            cids.forEach(cid->{
                brandMapper.insertCategoryBrand(cid,brand.getId());
            });
        }
    }

    @Override
    public void deleteById(Long bid) {
       brandMapper.deleteCategoryBrand(bid);
       brandMapper.deleteByPrimaryKey(bid);
    }

    @Override
    public List<Brand> findByCid(Long cid) {
        return brandMapper.findByCid(cid);
    }
}
